<template>
  <el-card class="permission-card">
    <div class="permission-title">{{ title }}</div>

    <!-- 按钮显示在标题下方 -->
    <el-button
        type="primary"
        icon="Plus"
        @click="dialogVisible = true"
        style="margin: 12px 0 20px 0;"
    >
      新增一级权限
    </el-button>

    <PermissionItem
        v-for="item in permissionGroups"
        :key="item.id"
        :item="item"
        :depth="0"
        :visited-ids="[]"
        @action="handlePermissionAction"
    />

    <!-- 新增权限弹窗 -->
    <el-dialog
        title="新增权限"
        v-model="dialogVisible"
        width="400px"
        @close="resetForm"
    >
      <el-form
          :model="form"
          ref="formRef"
          label-width="80px"
          :rules="rules"
          status-icon
      >
        <el-form-item label="权限名" prop="pname">
          <el-input v-model="form.pname" placeholder="请输入权限名" />
        </el-form-item>

        <el-form-item label="权限码" prop="permissionCode">
          <el-input v-model="form.code" placeholder="请输入权限码" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import axios from 'axios'
import PermissionItem from '@/views/Ye/PermissionItem.vue'
import {ElMessage} from "element-plus";

const route = useRoute()
const roleName = route.query.roleName || '系统管理'
const title = `${roleName} - 权限管理`

const permissionGroups = ref([])

// 控制弹窗显示
const dialogVisible = ref(false)

// 表单数据
const form = ref({
  pname: '',
  code: ''
})

// 表单验证规则
const rules = {
  pname: [
    { required: true, message: '请输入权限名', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限码', trigger: 'blur' }
  ]
}

const formRef = ref(null)

const handlePermissionAction = async (payload) => {
  if (typeof payload === 'string') {
    console.log('点击权限：', payload)
    return
  }

  const { type, item } = payload
  console.log(`[${type}] 权限项:`, item)

  try {
    if (type === 'add') {
      // 操作完成后刷新权限数据
      getPermissionForest()

    } else if (type === 'edit') {
      // 操作完成后刷新权限数据
      getPermissionForest()

    } else if (type === 'delete') {
      // 操作完成后刷新权限数据
      getPermissionForest()
    }

    // 操作完成后刷新权限数据
    getPermissionForest()
  } catch (err) {
    ElMessage.error('操作失败')
    console.error(err)
  }
}

// 新增权限按钮点击处理函数（保留）
const handleAddPermission = () => {
  console.log('点击了新增权限按钮')
  dialogVisible.value = true
}

const getPermissionForest = () => {
  axios.get('/permission/getPermissionForest').then(resp => {
    permissionGroups.value = resp.data
  }).catch(err => {
    console.error('获取权限树失败:', err)
  })
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    console.log('提交数据：', form.value)
    // TODO: 调接口提交新增权限
    await axios.post('/permission/addLevel1Perm', form.value).then( resp => {
      ElMessage.success("新增一级权限成功");
    })


    dialogVisible.value = false
    resetForm()
    getPermissionForest()
  } catch (error) {
    console.log('表单验证失败', error)
  }
}

// 重置表单
const resetForm = () => {
  form.value = {
    parentId: '',
    pname: '',
    permissionCode: ''
  }
  formRef.value?.clearValidate()
}

onMounted(() => {
  getPermissionForest()
})
</script>

<style scoped>
.permission-card {
  padding: 20px;
  background: #fff;
  min-height: 400px;
}

.permission-title {
  font-weight: bold;
  font-size: 18px;
  color: #333;
  margin-bottom: 8px;
}
</style>
